package com.xju.controller;

import com.xju.dao.UserDao;
import com.xju.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/UpdateUserInfoServlet")
public class UpdateUserInfoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String email = request.getParameter("email");

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user != null) {
            user.setUsername(username);
            user.setEmail(email);

            UserDao userDao = new UserDao();
            if (userDao.updateUser(user)) {
                session.setAttribute("user", user);
                session.setAttribute("updateMessage", "信息更新成功！");
                response.sendRedirect("myinfo.jsp");
            } else {
                request.setAttribute("errorMessage", "更新信息失败，请重试。");
                request.getRequestDispatcher("myinfo.jsp").forward(request, response);
            }
        } else {
            response.sendRedirect("login.jsp");
        }
    }
}
